<?php

class AdminRoleMenuService
{

    /*
     * 菜单 和 角色 是否有关联
     *
     */
    public static function checkMenuAndRole($menu_id,$role_id)
    {
        $admin_role_menu  = AdminRoleMenu::model()->find("role_id=:role_id and  menu_id=:menu_id",
            array(":role_id" => $role_id,":menu_id" => $menu_id));

        if(empty($admin_role_menu)==true)
            return 0;

        if($admin_role_menu->is_delete == 1)
            return 0;

        return 1;
    }

    //设置 菜单和角色关系
    public static function setRoleMenuRelation($role_id,$selectlist,$unselectlist)
    {
        $connection=Yii::app()->db;

        $transaction=$connection->beginTransaction();//事物开始

        $sarray = explode(",",$selectlist);
        $usarray = explode(",",$unselectlist);

        try
        {
            //设置选中状态
            $l = count($sarray);

            for($i=0;$i<$l;$i++)
            {
                $menu_id = $sarray[$i];

                AdminRoleMenuService::addRelation($role_id,$menu_id);

            }

            //取消选中状态
            $l = count($usarray);

            for($i=0;$i<$l;$i++)
            {
                $menu_id = $usarray[$i];

                AdminRoleMenuService::deleteRelation($role_id,$menu_id);

            }


            $transaction->commit();//事物结束

        }
        catch(Exception $e)
        {
            $transaction->rollback();//回滚函数

            throw new Exception($e->getMessage());

        }

    }

    //设置选中
    public static function addRelation($role_id,$menu_id)
    {
        $admin_role_menu  = AdminRoleMenu::model()->find("role_id=:role_id and  menu_id=:menu_id",
            array(":role_id" => $role_id,":menu_id" => $menu_id));

        if(empty($admin_role_menu)==true)
        {
            //新建
            $admin_role_menu = new AdminRoleMenu();

            $admin_role_menu->menu_id = $menu_id;
            $admin_role_menu->role_id = $role_id;
            Util::initObjData($admin_role_menu);

            Util::saveObjData($admin_role_menu);

        }
        else
        {
            //恢复
            if($admin_role_menu->is_delete == 1)
            {
                Util::recoverObjData($admin_role_menu);
                Util::saveObjData($admin_role_menu);
            }
        }



    }

    //取消选中
    public static function deleteRelation($role_id,$menu_id)
    {
        $admin_role_menu  = AdminRoleMenu::model()->find("role_id=:role_id and  menu_id=:menu_id",
            array(":role_id" => $role_id,":menu_id" => $menu_id));

        if(empty($admin_role_menu)==false)
        {
            //删除
            if($admin_role_menu->is_delete == 0)
            {
                Util::deleteObjData($admin_role_menu);
                Util::saveObjData($admin_role_menu);
            }

        }
        else
        {

        }



    }



}
?>